package com.derbysoft.lowcostadapter.commons.redis.service.impl;

import com.derbysoft.lowcostadapter.commons.model.RateCache;
import com.derbysoft.lowcostadapter.commons.redis.service.JedisClusterService;
import com.derbysoft.lowcostadapter.commons.redis.service.RateCacheService;
import com.derbysoft.lowcostadapter.commons.redis.service.RedisSerializable;
import com.derbysoft.lowcostadapter.commons.redis.utils.KeyValueHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by : jason
 * DateTime: 12-2-9
 */
@Component("rateCacheService")
public class RateCacheServiceImpl implements RateCacheService {

    @Autowired
    private JedisClusterService jedisClusterService;

    @Override
    public RateCache load(String key, String ratePlan, String roomType) {
        String field = ratePlan + KeyValueHelper.SEPARATOR + roomType;
        String value = jedisClusterService.hGet(key, field);
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return RateCache.build(key, field, value);
    }

    @Override
    public List<RateCache> loadAll(String key) {
        List<RateCache> rateCaches = new ArrayList<RateCache>();
        Map<String, RedisSerializable> rateCachesMap = jedisClusterService.hGetAll(key);
        for (RedisSerializable value : rateCachesMap.values()) {
            rateCaches.add((RateCache) value);
        }
        return rateCaches;
    }

    @Override
    public void remove(RateCache rateCache) {
        jedisClusterService.remove(rateCache.toKey(), rateCache.toFiled());
    }

    @Override
    public void remove(String key, String ratePlan, String roomType) {
        jedisClusterService.remove(key, ratePlan + KeyValueHelper.SEPARATOR + roomType);
    }

    @Override
    public void saveHSetEntities(List<HSetEntity> hSetEntities) {
        jedisClusterService.saveHSetEntities(hSetEntities);
    }

    @Override
    public void removeAll(String key) {
        jedisClusterService.removeAll(key);
    }

    @Override
    public void saveAll(List<RateCache> rateCaches) {
        jedisClusterService.pipelined(rateCaches);
    }
}
